<?php

namespace app\api\controller\v2;

use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Live;
use app\admin\model\cms\News;
use app\admin\model\cms\PlazaPostModel;
use app\admin\model\cms\RatingModel;
use app\admin\model\cms\Video;
use app\common\controller\Api;
use \app\admin\model\cms\Comment as CommentModel;
use app\admin\model\cms\Platepost;
use app\common\model\UserFavorite;
use app\common\model\UserLike;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use WeMeetingGateWay\HttpProxy;
use think\Cache;
/**
 * 评论
 */
class Comment extends Api
{
    //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedLogin = ['login', 'mobilelogin'];
    //无需鉴权的方法,但需要登录
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //获取评论列表/含评星
    public function inedx()
    {
        $request = $this->request->param();//获取提交的参数
        $user = $this->auth->getUser();//用户信息

        $type = $request['type'];//评论类型|news:新闻,bbs:论坛,video:视频,plaza:广场,album:专辑
        $aid = $request['aid'];//评论文章id
        $pid = $request['pid'] ?? 0;//评论父级id
        $top_pid = $request['top_pid'] ?? 0;//所属顶级评论id|pid=0的这条数据的id
        $orderway = $request['orderway'] ?? 'desc';//排序方式:asc,desc
        $page = $request['page'] ?? 1;//页码
        $limit = $request['limit'] ?? 20;//每页数量

        if (!$type || !$aid){
            $this->error('缺少参数');
        }

        switch ($type) {
            case 'album':
                $rating_table_name = 'album';
                break;
            case 'live':
                $rating_table_name = 'live';
                break;
            case 'video':
                $rating_table_name = 'video';
                break;
            default:
                $rating_table_name = '';//获取评分用的
        }


        $model = CommentModel::where('aid', $aid)
            ->where('type', $type)
            ->where('top_pid', $top_pid);
        if ($pid == 0) {
            $model->where('pid', 0);
        } elseif ($pid) {
            $model->where('pid', $pid);
        }
        $model = $model->order('id', $orderway)
            ->with(['children' => function ($query) {
                $query->with(['user']);
            },
                'user' => function ($query) use ($aid, $rating_table_name) {
                    if ($rating_table_name) {
                        $query->with(['rating' => function ($query) use ($aid, $rating_table_name) {
                            $query->where('object_id', $aid)->where('table_name', $rating_table_name);
                        }]);//管理评分
                    }
                }])
            ->paginate($limit, false, [
                'page' => $page,
                'query' => request()->param(),
            ])->toArray();
        $list = [];
        foreach ($model['data'] as $v) {
            $content = $v['content'];
            //判断是否为pid>1的评论,是则出现@上级评论发布者
            if ($v['pid'] > 0) {
                $pid_user = CommentModel::where('id', $v['pid'])->where('type', $type)->with(['user'])->field('id,user_id,type,status,pid')->find();
                if ($pid_user['pid']) {
                    $content = '@' . $pid_user['user']['username'] . ' ' . $v['content'];
                }
            }

            if (!$v['user']) {
                $v['user'] = \app\admin\model\User::getSoftDeleteUser($v['user_id']);
            }
            $v['user']['avatar'] = obsurl($v['user']['avatar']);

            $children = $v['children'] ?? [];//评论子集
            foreach ($children as $ck => &$cv) {
                if (!$cv['user']) {
                    $cv['user'] = \app\admin\model\User::getSoftDeleteUser($cv['user_id']);
                }
                $cv['user']['avatar'] = obsurl($cv['user']['avatar']);
                $cv['createtime'] = date('Y-m-d H:i:s', $cv['createtime']);
                $cv['updatetime'] = date('Y-m-d H:i:s', $cv['updatetime']);
                $cv['is_author'] = 0;//是否为评论作者|1:是,0:否
                if ($cv['user']['id'] == $user['id']) {
                    $cv['is_author'] = 1;//是否为评论作者|1:是,0:否
                }
            }

            $v['is_author'] = 0;//是否为评论作者|1:是,0:否
            if ($v['user']['id'] == $user['id']) {
                $v['is_author'] = 1;//是否为评论作者|1:是,0:否
            }

            $list[] = [
                'id' => $v['id'],
                'pid' => $v['pid'],
                'aid' => $v['aid'],
                'top_pid' => $v['top_pid'],
                'content' => $content,
                'content_text' => $v['content_text'],
                'content_files' => $v['content_files'] ?: '',
                'createtime' => date('Y-m-d H:i:s', $v['createtime']),
                'user' => [
                    'id' => $v['user']['id'],
                    'nickname' => $v['user']['nickname'],
                    'avatar' => $v['user']['avatar'],
                ],
                'rating_score' => $v['user']['rating'][0]['score'] ?? 0,//文章/专辑评分
                'children' => $children,//子集评论
                'is_children' => in_array($type, array_column($v['children'], 'type')) ? 1 : 0,//是否存在子集|0:否,1:是
//                'children'=>$v['children']
                'is_author' => $v['is_author'],//是否为评论作者|1:是,0:否
                'aaa' => 0,//前端使用,用来判断是否修改文章,这个字段在后端无意义,固定就返回0
            ];
        }
        $res = [
            'list' => $list,
            'pid' => $model['data'][0]['pid'] ?? 0,
            'total' => $model['total'],
            'current_page' => $model['current_page']//当前所在页数
        ];
        $this->success('', $res);
    }

    //添加评论
    public function addComment()
    {
        $request = $this->request->param();//获取提交的参数
        //参数验证
        $rule = [
            'type|评论类型' => 'require',
            'content|评论内容' => 'require',
            'aid|评论文章id' => 'require|integer',
        ];
        $msg = [
            'type.require' => '评论类型不能为空',
            'content.require' => '评论内容不能为空',
            'aid.require' => '评论文章id不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($request);
        if (!$result) {
            $this->error($validate->getError());
        }

        $user = $this->auth->getUser();//用户信息
        $type = $request['type'];//评论类型|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播,album:专辑
        $aid = $request['aid'];//评论文章id
        $pid = $request['pid'] ?? 0;//评论父级id
        $top_pid = $request['top_pid'] ?? 0;//所属顶级评论id|pid=0的这条数据的id
        $image = $request['image'] ?? [];
        if (!$image){
            $image = [];
        }
        $content_files = trim(implode(',',$image),',');//评论文件中的文件地址
        $content = $this->markdownToHtml($request['content']);//评论内容 Markdown 转 富文本html
        $content_text = $this->request->param('con','');//评论内容纯文本
        // 微信内容过滤
        if($this->request->param('form_type') === 'mini'){
            $wxaccess_token = Cache::get('wxaccess_token');

            if(!$wxaccess_token){
                $http_proxy =  new HttpProxy();
                $response = $http_proxy->sendRequest('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx26182c3e34af2dc5&secret=d6ff61d88d95b7a098d2c69ea5ae0c12', 'GET');
                $response = json_decode($response,true);
                Cache::set('wxaccess_token', $response['access_token'] ?? '', $response['expires_in']);
                $wxaccess_token = $response['access_token'] ?? '';
            }
            $encodings = ['GB18030', 'GBK', 'BIG5', 'ISO-8859-1', 'UTF-8'];
            foreach ($encodings as $encoding) {
                try {
                    $utf8String = mb_convert_encoding($content_text, 'UTF-8', $encoding);
                    if (mb_check_encoding($utf8String, 'UTF-8')) {

                        break;
                    }
                } catch (\Exception $e) {
                    continue;
                }
            }
            $handlcontenturl = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='.$wxaccess_token;
            $http_proxy =  new HttpProxy();
            $response = $http_proxy->sendRequest($handlcontenturl,
                'POST',
                ['Content-Type: application/json; charset=utf-8'],
                json_encode(['content'=>$content_text,'version'=>2,'scene'=>2,'openid'=>$user['wechat_openid']],JSON_UNESCAPED_UNICODE)
            );
            $response = json_decode($response,true);

            if($response['result'] !=='pass'){
                $this->error('您评论的内容违规禁止发布');
            }
        }

        //判断如果添加的是否2级或以上的子集id top_pid就不可能是0,只有pid==0时top_pod才能是0
        if ($pid > 0 && $top_pid <= 0) {
            $this->error('所属顶级评论id');
        } elseif ($pid == 0 && $top_pid != 0) {
            $this->error('所属顶级评论id');
        }

        $model = null;
        switch ($type) {
            case 'news':
                $model = News::find($aid);
                $table_name = 'news';
                break;
            case 'bbs':
                $model = Platepost::find($aid);
                $table_name = 'plate_post';
                break;
            case 'video':
                $model = Video::find($aid);
                $table_name = 'video';
                break;
            case 'plaza':
                $model = PlazaPostModel::find($aid);
                $table_name = 'plaza_post';
                break;
            case 'live':
                $model = Live::find($aid);
                $table_name = 'live';
                break;
            case 'album':
                $model = AlbumModel::find($aid);
                $table_name = 'album';
                break;
            default:
                $this->error('类型正确');
        }
        if (!$model) {
            $this->error('文章/内容不存在');
        }
        $useragent = substr(request()->server('HTTP_USER_AGENT', ''), 0, 255);
        $ip = request()->ip(0, false);

        Db::startTrans();//开启事物
        try {
            //添加评论
            $success = \app\common\model\Comment::create([
                'user_id' => $user['id'],
                'type' => $type,
                'aid' => $aid,
                'pid' => $pid,
                'top_pid' => $top_pid,
                'content' => $content,
                'content_text' => $content_text,
                'content_files' => $content_files,
                'comments' => 0,
                'ip' => $ip,
                'useragent' => $useragent,
                'status' => 'normal',//状态|normal:正常
            ]);
            if ($type == 'video') {
                $model->setInc('count_comment');//增加文章评论数量
            } elseif (!in_array($type, ['album', 'live'])) {
                $model->setInc('comment_count');//增加文章评论数量
            }
            Db::commit();//提交事物
        } catch (Exception $exception) {
            Db::rollback();//回滚事物
            $this->error('失败原因:' . $exception->getMessage());
        }

        $res = CommentModel::with(['user'])
            ->find($success['id'])
            ->toArray();
        if ($top_pid == 0) {
            $res['top_pid'] = $success['id'];
        }
        $res['createtime'] = date('Y-m-d H:i:s', $res['createtime']);
        if ($res['pid'] > 0) {
            $pid_user = CommentModel::where('id', $res['pid'])->where('type', $type)->with(['user'])->field('id,user_id,type,status,pid')->find();
            if ($pid_user['user']) {
                $res['content'] = '@' . $pid_user['user']['username'] . ' ' . $res['content'];
            }
        }
        //增加相应积分
        $score = new Score();
        $score->editScore($user['id'], $aid, 'comment_score', 1, $table_name);//发起评论

        $this->success('评论添加成功', $res);
    }

    //更新评论
    public function updateComment()
    {
        $request = $this->request->param();
        $id = $this->request->param('id', '');//评论id'
        $content = $this->request->param('content', '');//评论内容
        $content = $this->markdownToHtml($content);////评论内容 Markdown 转 富文本html

        $image = $request['image'] ?? [];
        $content_files = trim(implode(',',$image),',');//评论文件中的文件地址
        $content_text = $this->request->param('con','');//评论内容纯文本

        $user = $this->auth->getUser();//用户信息
        $comment_model = CommentModel::where('id', $id)
            ->where('user_id', $user['id'])
            ->find();
        if (!$comment_model) {
            $this->success('评论不存在');
        }
        $update = CommentModel::where('id', $id)
            ->where('user_id', $user['id'])
            ->update([
                'content' => nl2br($content),
                'content_text' => $content_text,
                'content_files' => $content_files,
            ]);
        $this->success('操作成功');
    }

    //删除评论
    public function delComment()
    {
        $id = $this->request->param('id', '');//评论id'
        $user = $this->auth->getUser();//用户信息
        $comment_model = CommentModel::where('id', $id)
            ->where('user_id', $user['id'])
            ->find();
        if (!$comment_model) {
            $this->success('删除成功');
        }

        Db::startTrans();
        try {
            //找到当前评论的全部下级然后进行删除
            if ($comment_model['pid'] == 0) {
                $success1 = CommentModel::where('id', $id)->update(['deletetime' => time()]);//删除主评论
                $success2 = CommentModel::where('top_pid', $id)->update(['deletetime' => time()]);//删除全部子评论
            } else {
                $obj = new CommentModel();
                $del_pid_arr = $obj->deleteCommentAndChildren($id);//查询全部的子集
                $success1 = CommentModel::where('id', $id)->update(['deletetime' => time()]);//删除主评论
                $success2 = 0;
                if ($del_pid_arr){
                    $success2 = CommentModel::whereIn('pid', $del_pid_arr)->update(['deletetime' => time()]);//删除子评论
                }
            }

            //根据评论类型更新不同表中的评论数量
            switch ($comment_model['type']) {
                case 'news':
                    $model = News::find($comment_model['aid']);
                    break;
                case 'bbs':
                    $model = Platepost::find($comment_model['aid']);
                    break;
                case 'video':
                    $model = Video::find($comment_model['aid']);
                    break;
                case 'plaza':
                    $model = PlazaPostModel::find($comment_model['aid']);
                    break;
                case 'live':
                    $model = Live::find($comment_model['aid']);
                    break;
                case 'album':
                    $model = AlbumModel::find($comment_model['aid']);
                    break;
                default:
                    $model = null;
            }
            if ($model) {
                $del_num = $success1 + $success2;
                if ($comment_model['type'] == 'video') {
                    if ($model['count_comment'] > 0) {
                        $del_num = $model['count_comment'] - $del_num;
                        if ($del_num < 0){
                            $del_num = 0;
                        }
                        $model->count_comment = $del_num;
                        $model->save();//减少文章评论数量
                    }
                } elseif (!in_array($comment_model['type'], ['album', 'live'])) {
                    if ($model['comment_count'] > 0) {
                        $del_num = $model['comment_count'] - $del_num;
                        if ($del_num < 0){
                            $del_num = 0;
                        }
                        $model->comment_count = $del_num;
                        $model->save();//减少文章评论数量
                    }
                }
            }
            Db::commit();
            $this->success('操作成功');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error('操作失败', ['err' => $exception->getMessage()]);
        }
    }

    /**
     * 添加点赞
     * @param $user 用户信息
     * @param $table_name 内容以前所在表,不带前缀
     * @param $object_id 内容原来的主键id
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function addLive($user, $table_name, $object_id)
    {

        switch ($table_name) {
            //新闻
            case 'news':
                $model = News::where('id', $object_id)->find();
                break;
            //广场
            case 'plaza_post':
                $model = PlazaPostModel::where('id', $object_id)->find();
                break;
            //视频
            case 'video':
                $model = Video::where('id', $object_id)->find();
                break;
            //论坛
            case 'plate_post':
                $model = Platepost::where('id', $object_id)->find();
                break;
            //直播
            case  'live':
                $model = Live::where('id', $object_id)->find();
                break;
            default:
                return [
                    'code' => 200,
                    'data' => []
                ];
        }

        $user_like = UserLike::where('table_name', $table_name)
            ->where('object_id', $object_id)
            ->where('user_id', $user['id'])
            ->find();
        if ($user_like) {
            if ($table_name == 'video') {
                $post_like = $model['count_like'] ?? 0;
            } else {
                $post_like = empty($model['post_like']) ? (UserLike::likeTotal($model['id'], $table_name) ?? 0) : 0;
            }
            return [
                'code' => 200,
                'data' => ['post_like' => $post_like]
            ];
        }

        $success = UserLike::create([
            'user_id' => $user['id'],
            'object_id' => $object_id,
            'table_name' => $table_name,
        ]);

        if ($table_name == 'video') {
            $model->setInc('count_like');//点赞数量自增+1
            $post_like = $model['count_like'];
        } else if ($table_name == 'live') {
            $post_like = UserLike::likeTotal($model['id'], $table_name) ?? 0;
        } else {
            $model->setInc('post_like');//点赞数量自增+1
            $post_like = $model['post_like'];
        }

        if (!$success) {
            return [
                'code' => 500,
                'data' => [],
            ];
        }
        return [
            'code' => 200,
            'data' => ['post_like' => $post_like]
        ];
    }

    /**
     * 取消点赞
     * @param $user 用户信息
     * @param $table_name 内容以前所在表,不带前缀
     * @param $object_id 内容原来的主键id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function delLive($user, $table_name, $object_id)
    {
        switch ($table_name) {
            //新闻
            case 'news':
                $model = News::where('id', $object_id)->find();
                break;
            //广场
            case 'plaza_post':
                $model = PlazaPostModel::where('id', $object_id)->find();
                break;
            //视频
            case 'video':
                $model = Video::where('id', $object_id)->find();
                break;
            //论坛
            case 'plate_post':
                $model = Platepost::where('id', $object_id)->find();
                break;
            default:
                return [
                    'code' => 200,
                    'data' => []
                ];
        }
        if (!$model) {
            $this->error('文章内容不存在');
        }

        $user_like = UserLike::where('table_name', $table_name)
            ->where('object_id', $object_id)
            ->where('user_id', $user['id'])
            ->find();
        if (!$user_like) {
            if ($table_name == 'video') {
                $post_like = $model['count_like'] ?? 0;
            } else {
                $post_like = $model['post_like'] ?? 0;
            }
            return [
                'code' => 200,
                'data' => ['post_like' => $post_like]
            ];
        }


        $success = $user_like->delete();

        if ($table_name == 'video') {
            $model->setDec('count_like');//点赞数量自减-1
            $post_like = $model['count_like'];
        } else {
            $model->setDec('post_like');//点赞数量自减-1
            $post_like = $model['post_like'];
        }
        if (!$success) {
            return [
                'code' => 500,
                'data' => []
            ];
        }

        return [
            'code' => 200,
            'data' => ['post_like' => $post_like]
        ];
    }

    //添加收藏
    public function addFavorite()
    {
        $request = $this->request->param();//获取提交的参数
        $user = $this->auth->getUser();//用户信息
        $table_name = $request['table_name'];//内容以前所在表,不带前缀
        $object_id = $request['object_id'];//内容原来的主键id|table_name表名下的id

        switch ($table_name) {
            //新闻
            case 'news':
                $model = News::where('id', $object_id)->find();
                break;
            //广场
            case 'plaza_post':
                $model = PlazaPostModel::where('id', $object_id)->find();
                break;
            //视频
            case 'video':
                $model = Video::where('id', $object_id)->find();
                break;
            //论坛
            case 'plate_post':
                $model = Platepost::where('id', $object_id)->find();
                break;
            //专辑
            case 'album':
                $model = AlbumModel::where('id', $object_id)->find();
                break;
            default:
                $this->error('收藏类型不正确');
        }

        //参数验证
        $rule = [
            'object_id|内容原来的主键id' => 'require|integer',
        ];
        $msg = [
            'object_id.require' => '内容原来的主键id不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($request);
        if (!$result) {
            $this->error($validate->getError());
        }
        if (!$model) {
            $this->error('文章内容/专辑不存在');
        }

        $user_favorite = UserFavorite::where('table_name', $table_name)
            ->where('object_id', $object_id)
            ->where('user_id', $user['id'])
            ->find();
        if ($user_favorite) {
            if ($table_name == 'video') {
                $post_favorites = $model['count_favorite'] ?? 0;
            } else {
                $post_favorites = $model['post_favorites'] ?? 0;
            }
            $this->success('收藏成功', ['post_favorites' => $post_favorites]);
        }

        Db::startTrans();//开启事物
        try {
            $success = UserFavorite::create([
                'user_id' => $user['id'],
                'object_id' => $object_id,
                'table_name' => $table_name,
            ]);

            if ($table_name == 'video') {
                $model->setInc('count_favorite');//收藏数量自增+1
                $post_favorites = $model['count_favorite'];
            } elseif ($table_name == 'album') {
                $post_favorites = 1;
            } else {
                $model->setInc('post_favorites');//收藏数量自增+1
                $post_favorites = $model['post_favorites'];
            }
            if (!$success) {
                Db::rollback();
                $this->error('收藏失败');
            }

            $addLive = $this->addLive($user, $table_name, $object_id);//添加点赞
            if ($addLive['code'] != 200){
                Db::rollback();
                $this->error('收藏失败');
            }

            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error('失败原因:' . $exception->getMessage());
        }

        //增加相应积分
        $score = new Score();
        $score->editScore($user['id'], $object_id, 'favorite_score', 1, $table_name);//发起收藏
        if ($table_name != 'album') {
            $score->editScore($model['user_id'], $object_id, 'by_favorite_score', 1, $table_name);//被收藏
        }

        $this->success('收藏成功', ['post_favorites' => $post_favorites]);
    }

    //取消收藏
    public function delFavorite()
    {
        $request = $this->request->param();//获取提交的参数
        $user = $this->auth->getUser();//用户信息
        $table_name = $request['table_name'];//内容以前所在表,不带前缀
        $object_id = $request['object_id'];//内容原来的主键id

        switch ($table_name) {
            //新闻
            case 'news':
                $model = News::where('id', $object_id)->find();
                break;
            //广场
            case 'plaza_post':
                $model = PlazaPostModel::where('id', $object_id)->find();
                break;
            //视频
            case 'video':
                $model = Video::where('id', $object_id)->find();
                break;
            //论坛
            case 'plate_post':
                $model = Platepost::where('id', $object_id)->find();
                break;
            //专辑
            case 'album':
                $model = AlbumModel::where('id', $object_id)->find();
                break;
            default:
                $this->error('类型不正确');
        }
        if (!$model) {
            $this->error('文章内容/专辑不存在');
        }

        //参数验证
        $rule = [
            'object_id|内容原来的主键id' => 'require|integer',
        ];
        $msg = [
            'object_id.require' => '内容原来的主键id不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($request);
        if (!$result) {
            $this->error($validate->getError());
        }

        $user_favorite = UserFavorite::where('table_name', $table_name)
            ->where('object_id', $object_id)
            ->where('user_id', $user['id'])
            ->find();
        if (!$user_favorite) {
            if ($table_name == 'video') {
                $post_favorites = $model['count_favorite'] ?? 0;
            } else {
                $post_favorites = $model['post_favorites'] ?? 0;
            }
            $this->success('取消收藏成功', ['post_favorites' => $post_favorites]);
        }

        Db::startTrans();//开启事物
        try {
            $success = $user_favorite->delete();

            if ($table_name == 'video') {
                $model->setDec('count_favorite');//点赞数量自减-1
                $post_favorites = $model['count_favorite'] ?? 0;
            } elseif ($table_name == 'album') {
                $post_favorites = 0;
            } else {
                $model->setDec('post_favorites');//点赞数量自减-1
                $post_favorites = $model['post_favorites'] ?? 0;
            }

            //减少相应积分
            $score = new Score();
            $score->editScore($user['id'], $object_id, 'favorite_score', 2, $table_name);//取消发起收藏
            //专辑是admin发起的,所以admin是不会得到积分的
            if ($table_name != 'album') {
                $score->editScore($model['user_id'], $object_id, 'by_favorite_score', 2, $table_name);//取消被收藏
            }

            if (!$success) {
                Db::rollback();
                $this->error('取消收藏失败');
            }

            $addLive = $this->delLive($user, $table_name, $object_id);//取消点赞
            if ($addLive['code'] != 200){
                Db::rollback();
                $this->error('取消收藏失败');
            }

            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error('失败原因:' . $exception->getMessage());
        }

        $this->success('取消收藏成功', ['post_favorites' => $post_favorites]);
    }

    //转发回调
    public function repostCallback()
    {
        $request = $this->request->param();//获取提交的参数
        $user = $this->auth->getUser();//用户信息
        $table_name = $request['table_name'];//内容以前所在表,不带前缀
        $object_id = $request['object_id'];//内容原来的主键id

        switch ($table_name) {
            //新闻
            case 'news':
                $model = News::where('id', $object_id)->find();
                break;
            //广场
            case 'plaza_post':
                $model = PlazaPostModel::where('id', $object_id)->find();
                break;
            //视频
            case 'video':
                $model = Video::where('id', $object_id)->find();
                break;
            //论坛
            case 'plate_post':
                $model = Platepost::where('id', $object_id)->find();
                break;
            //专辑
            case 'album':
                $model = AlbumModel::where('id', $object_id)->find();
                break;
            default:
                $this->error('转发类型不正确');
        }

        //参数验证
        $rule = [
            'object_id|内容原来的主键id' => 'require|integer',
        ];
        $msg = [
            'object_id.require' => '内容原来的主键id不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($request);
        if (!$result) {
            $this->error($validate->getError());
        }
        if (!$model) {
            $this->error('文章内容/专辑不存在');
        }

        //增加转发数量
        if ($table_name == 'video') {
            $model->setInc('count_forward');//转发数量自增+1
        } elseif ($table_name == 'album') {

        } else {
            $model->setInc('post_forward');//转发数量自增+1
        }

        //增加相应积分
        $score = new Score();
        $a1 = $score->editScore($user['id'], $object_id, 'repost_score', 1, $table_name);//发起转发
        $a2 = $score->editScore($model['user_id'], $object_id, 'by_repost_score', 1, $table_name);//被转发

        $this->success('');
    }

    //内容/专辑(评分/评星)
    public function addRating()
    {
        $request = $this->request->param();//获取提交的参数
        $user = $this->auth->getUser();//用户信息

        $table_name = $request['table_name'];//来源的表名|不带表名前缀
        $object_id = $request['object_id'];//被打分作品的id|table_name表名下的id值
        $score = $request['score'];//分数|1分=1颗星星

        //参数验证
        $rule = [
            'table_name|评分类型' => 'require',
            'object_id|评分内容' => 'require|integer',
            'score|评分' => 'require',
        ];
        $msg = [
            'table_name.require' => '来源不能为空',
            'object_id.require' => '被打分作品的id不能为空',
            'score.require' => '分数不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($request);
        if (!$result) {
            $this->error($validate->getError());
        }
        if (!in_array($table_name, ['video', 'live', 'album'])) {
            $this->error('评分类型不正确');
        }

        //评分表->有则修改评分,无则创建评分
        $model = RatingModel::where('object_id', $object_id)
            ->where('table_name', $table_name)
            ->where('user_id', $user['id'])
            ->find();
        if ($model) {
            //更新评分
            $success = RatingModel::where('id', $model['id'])->update([
                'score' => $score,
            ]);
        } else {
            //插入评分记录
            $success = RatingModel::create([
                'table_name' => $table_name,
                'object_id' => $object_id,
                'score' => $score,
                'user_id' => $user['id'],
            ]);
        }

        //计算平均分
        $average_score = RatingModel::where('table_name', $table_name)
            ->where('object_id', $object_id)
            ->avg('score');

        // 四舍五入保留1位小数
        $average_score = round($average_score, 1);
        switch ($table_name) {
            case 'video'://视频
                Video::where('id', $object_id)->update(['average_score' => $average_score]);
                $album_id = Video::where('id', $object_id)->value('album_id') ?? 0;//所属专辑id
                if ($album_id) {
                    $video_ids = Video::where('album_id', $album_id)->column('id');
                    if ($video_ids) {
                        $album_average_score = RatingModel::where('table_name', 'video')
                            ->whereIn('object_id', $video_ids)
                            ->avg('score');
                        //获取这个视频所属专辑下的全部视频并求平均分
                        AlbumModel::where('id', $album_id)->update(['average_score' => $album_average_score]);
                    }
                }
                break;
            case 'live'://直播
                Live::where('id', $object_id)->update(['average_score' => $average_score]);
                break;
            case 'album'://专辑
                AlbumModel::where('id', $object_id)->update(['average_score' => $average_score]);
                break;
        }


        $res = [
            'table_name' => $table_name,
            'object_id' => $object_id,
            'score' => $score,
        ];
        $this->success('', $res);
    }

}
